package cn.sky.demo.test.latchutils;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ManualCountDownLatchExample {

    public static void main(String[] args) {
        // 1. 准备一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        
        // 2. 手动初始化 CountDownLatch，数量为任务数
        CountDownLatch latch = new CountDownLatch(3);

        System.out.println("主流程开始，准备分发异步任务...");

        // 3. 提交任务，并在每个任务的 finally 块中手动调用 latch.countDown()
        // 任务一：获取用户信息
        executorService.execute(() -> {
            try {
                System.out.println("开始获取用户信息...");
                Thread.sleep(1000);
                System.out.println("获取用户信息成功！");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                latch.countDown(); // 手动减一
            }
        });

        // 任务二：获取订单信息
        executorService.execute(() -> {
            try {
                System.out.println("开始获取订单信息...");
                Thread.sleep(1500);
                System.out.println("获取订单信息成功！");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                latch.countDown(); // 手动减一
            }
        });

        // 任务三：获取商品信息
        executorService.execute(() -> {
            try {
                System.out.println("开始获取商品信息...");
                Thread.sleep(500);
                System.out.println("获取商品信息成功！");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                latch.countDown(); // 手动减一
            }
        });

        System.out.println("所有异步任务已提交，主线程开始等待...");

        // 4. 手动调用 latch.await() 进行等待
        boolean allTasksCompleted = false;
        try {
            allTasksCompleted = latch.await(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // 需要处理中断异常
            Thread.currentThread().interrupt();
            System.err.println("主线程在等待时被中断！");
        }
        
        // 5. 根据等待结果继续主流程
        if (allTasksCompleted) {
            System.out.println("所有异步任务执行成功，主流程继续...");
        } else {
            System.err.println("有任务执行超时，主流程中断！");
        }
        
        // 6. 关闭线程池
        executorService.shutdown();
    }
}